package com.cos.hospital.tool.takephoto;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;

import com.cos.hospital.R;
import com.cos.hospital.code.Code;
import com.cos.hospital.init.BaseActivity;
import com.cos.hospital.tool.FileUtil;
import com.cos.hospital.tool.ULog;
import com.cos.hospital.tool.glide.GlideApp;
import com.google.android.cameraview.CameraView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.kareluo.imaging.IMGEditActivity;
import top.zibin.luban.Luban;

/**
 * 拍照
 */
public class CameraActivity extends BaseActivity {
    private static final int REQUEST_EDIT_IMAGE_CODE = 99;
    @BindView(R.id.camera)
    CameraView cameraView;
    @BindView(R.id.iv_photo)
    ImageView iv_photo;
    @BindView(R.id.iv_switch)
    ImageView iv_switch;
    @BindView(R.id.iv_back)
    ImageView iv_back;
    @BindView(R.id.iv_cancel)
    ImageView iv_cancel;
    @BindView(R.id.iv_camera)
    ImageView iv_camera;
    @BindView(R.id.iv_edit)
    ImageView iv_edit;
    @BindView(R.id.iv_confirm)
    ImageView iv_confirm;
    private String photoPath;
    private String targerFilePath;

    @Override
    protected int layout() {
        return R.layout.activity_camera;
    }

    @Override
    protected void init() {
    }

    @Override
    protected void logic() {
        cameraView.addCallback(new CameraView.Callback() {
            @Override
            public void onPictureTaken(CameraView cameraView, byte[] data) {
                saveAndShow(cameraView, data);
            }
        });
    }

    @OnClick(R.id.iv_switch)
    public void switchCamera() {
        int facing = cameraView.getFacing();
        if (facing == CameraView.FACING_BACK) {
            cameraView.setFacing(CameraView.FACING_FRONT);
        } else {
            cameraView.setFacing(CameraView.FACING_BACK);
        }
    }

    @OnClick(R.id.iv_back)
    public void back() {
        finish();
    }

    @OnClick(R.id.iv_cancel)
    public void cancel() {
        cameraView.start();
        changeUI(false);
    }

    @OnClick({R.id.iv_camera})
    public void camera() {
        cameraView.takePicture();
    }

    @OnClick({R.id.iv_edit})
    public void editImage() {
        targerFilePath = FileUtil.getExternalCacheDir(this) + File.separator + System.currentTimeMillis() + ".jpg";
        Intent intent = new Intent(this, IMGEditActivity.class);
        intent.putExtra(IMGEditActivity.EXTRA_IMAGE_URI, Uri.fromFile(new File(photoPath)));
        intent.putExtra(IMGEditActivity.EXTRA_IMAGE_SAVE_PATH, targerFilePath);
        startActivityForResult(intent, REQUEST_EDIT_IMAGE_CODE);
    }

    @OnClick({R.id.iv_confirm})
    public void confirm() {
        Intent intent = new Intent();
        intent.putExtra(Code.SP.SAVEPATH, photoPath);
        setResult(Activity.RESULT_OK, intent);
        finish();
    }

    private void saveAndShow(CameraView cameraKitView, byte[] capturedImage) {
        Observable
            .create((ObservableOnSubscribe<File>) emitter -> {
                File savedPhoto = new File(FileUtil.getExternalCacheDir(this), System.currentTimeMillis() + ".jpg");
                try {
                    FileOutputStream outputStream = new FileOutputStream(savedPhoto.getPath());
                    outputStream.write(capturedImage);
                    outputStream.close();
                } catch (IOException e) {
                    ULog.d(e.toString());
                }
                List<File> fileList = Luban.with(this)
                    .load(new File(savedPhoto.getPath()))
                    .ignoreBy(100)
                    .get();
                if (fileList != null && fileList.size() != 0) {
                    emitter.onNext(fileList.get(0));
                }
            })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(file -> {
                cameraKitView.stop();
                photoPath = file.getPath();
                showImage();
                changeUI(true);
            });
    }

    /**
     * complete 已拍照
     */
    private void changeUI(boolean complete) {
        int visible = complete ? View.VISIBLE : View.GONE;
        int gone = complete ? View.GONE : View.VISIBLE;
        iv_switch.setVisibility(gone);
        iv_photo.setVisibility(visible);
        iv_back.setVisibility(gone);
        iv_cancel.setVisibility(visible);
        iv_camera.setVisibility(gone);
        iv_edit.setVisibility(visible);
        iv_confirm.setVisibility(visible);
    }

    private void showImage() {
        GlideApp.with(this)
            .load(photoPath)
            .fitCenter()
            .into(iv_photo);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                //图片编辑
                case REQUEST_EDIT_IMAGE_CODE:
                    photoPath = targerFilePath;
                    showImage();
                    break;
            }
        }
    }

    @Override
    public void onBackPressed() {
        if (iv_cancel.getVisibility() == View.VISIBLE) {
            cancel();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onResume() {
        super.onResume();
        cameraView.start();
    }

    @Override
    protected void onPause() {
        cameraView.stop();
        super.onPause();
    }

}
